package com.sopaths.crawler.zhilian;

import java.net.URI;
import java.net.URISyntaxException;

import javax.inject.Named;

import org.apache.http.client.utils.URIBuilder;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.sopaths.crawler.SummaryTotalPageCrawler;
import com.sopaths.crawler.tasks.SummaryTotalPageCrawlerTask;

@Named
public class ZhiLianSummaryTotalPageCrawler extends SummaryTotalPageCrawler {

	private Logger logger = Logger.getLogger(ZhiLianSummaryTotalPageCrawler.class);

	@Override
	protected String assembleSummaryTotalPageUrl(SummaryTotalPageCrawlerTask task) {
		try {
			URI uri = new URIBuilder().setScheme("http")
					.setHost("sou.zhaopin.com")
					.setPath("/Jobs/searchresult.ashx")
					.setParameter("jl", task.getCity().getName())
					.setParameter("sm", "0")
					.setParameter("p", "1")
					.setParameter("sf", "0").build();
			return uri.toString();
		} catch (URISyntaxException ex) {
			logger.error("An error occurred while assembling URL.", ex);
			throw new RuntimeException(ex);
		}
	}

	@Override
	protected void assembleSummaryTotalPageTaskResult(SummaryTotalPageCrawlerTask task, Document document) {
		Elements elements = document.select(".pagesDown ul li:nth-last-child(4) a");
		for (Element element : elements) {
			task.setResult(Integer.parseInt(element.text()));
		}
	}
/*
	@Override
	public void crawl(CrawlerTask<?> task) {
		try {
			SummaryTotalPageCrawlerTask innerTask = (SummaryTotalPageCrawlerTask) task;

			URI uri = new URIBuilder().setScheme("http")
					.setHost("sou.zhaopin.com")
					.setPath("/Jobs/searchresult.ashx")
					.setParameter("jl", innerTask.getCity().getName())
					.setParameter("sm", "0")
					.setParameter("p", "1")
					.setParameter("sf", "0").build();
			HttpGet httpGet = new HttpGet(uri);
			try (CloseableHttpResponse response = getHttpClient().execute(httpGet)) {
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
				Document document = Jsoup.parse(html);
				Elements elements = document.select(".pagesDown ul li:nth-last-child(4) a");
				for (Element element : elements) {
					innerTask.setResult(Integer.parseInt(element.text()));
				}
			}
		} catch (Exception ex) {
			logger.error("An error occurred while crawling.", ex);
		}
	}
*/
}
